#include "mysockets.h"

int request_connection(char * host, int port){

  struct sockaddr_in sock;
  struct hostent * he;
  int s;
  int okflag;
  
  //try to get the host name specified by the user
  if(!(he = gethostbyname(host))){
	fprintf(stderr, "Invalid host name: %s\n",host);
	exit(1);
  }
  
  for(okflag = 0; !okflag; ){

	//set the socket to IPv4
 	sock.sin_family = AF_INET;

	//convert i/o to handle big/little endian
	sock.sin_port = htons((short)port);

	//set the socket address
	sock.sin_addr.s_addr = *(u_long *)(he->h_addr_list[0]);

	//create the socket
	if((s = socket(AF_INET, SOCK_STREAM, 0)) == -1){
		perror("socket()");
		exit(1);
	}

	//connect to the socket
	okflag = (connect(s, (struct sockaddr *)&sock, sizeof(sock)) != -1);

	//if connection failed, wait for 1 second and try again
	if(!okflag){
		sleep(1);
	}
  }

  //return file descriptor of port
  return s;

}

int serve_socket(char * host, int port){

  struct sockaddr_in sock;
  struct hostent *he;
  int s;

  
  if(!(he = gethostbyname(host))){
	fprintf(stderr, "Invalid host name: %s\n",host);
	exit(1);
  }

  bzero((char*)&sock, sizeof(sock));
  
  //set the socket to IPv4
  sock.sin_family = AF_INET;

  //convert i/o to handle big/little endian
  sock.sin_port = htons((short)port);

  //set the socket address
  sock.sin_addr.s_addr = *(u_long *)(he->h_addr_list[0]);

  //create the socket
  if((s = socket(AF_INET, SOCK_STREAM, 0)) == -1){
	perror("socket()");
	exit(1);
  }

  //bind the socket
  if(bind(s, (struct sockaddr *)&sock, sizeof(sock)) == -1){
	perror("bind()");
	exit(1);
  }

  return(s);

}

//wait on and accept socket connection
int accept_connection(int s){

  int l;
  int x;
  struct sockaddr_in sock;

  //set the socket to IPv4
  sock.sin_family = AF_INET;

  if(listen(s, 1) == -1){
	perror("listen()");
	exit(1);
  }

  l = sizeof(sock);

  if((x = accept(s, (struct sockaddr*)&sock, &l)) == -1){
	perror("accept()");
	exit(1);
  }

  return(x);

}
